﻿package com.projects.xenia.prompts_activities;

import java.io.File;
import java.util.ArrayList;

import javax.xml.datatype.Duration;


import com.projects.xenia.R;
import com.projects.xenia.Documents_Location.GPSStateEnum;
import com.projects.xenia.add_activities.Activity_SalesHistory;
import com.projects.xenia.documents_classes.Documents_Blank;
import com.projects.xenia.documents_classes.Documents_Order;
import com.projects.xenia.documents_classes.Documents_Order.DocLine;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.ref_classes.GoodsRefItem;
import com.projects.xenia.ref_classes.SalesRefItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.KeyEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;

import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

public class Activity_OrderGoodsPrompt extends Activity {
	
	private Animation slide_in_left, slide_out_left, slide_in_right, slide_out_right;

	private Context Ctx;
	private final int IDD_MeasuresDialog = 0;
	
	private Button OrderPrompt_Enter;	
	private Button OrderPrompt_One;
	private Button OrderPrompt_Two;
	private Button OrderPrompt_Three;
	private Button OrderPrompt_Four;
	private Button OrderPrompt_Five;
	private Button OrderPrompt_Six;
	private Button OrderPrompt_Seven;
	private Button OrderPrompt_Eight;
	private Button OrderPrompt_Nine;
	private Button OrderPrompt_Null;	
	private Button OrderPrompt_Point;
	private Button OrderPrompt_Clear;	
	private Button OrderPrompt_BackSpace;	
	private Button OrderPrompt_Measures;	
	private TextView OrderPrompt_GoodsDescr;	
	private TextView OrderPrompt_Price;
	private TextView OrderPrompt_GoodsRest;	
	private TextView OrderPrompt_Rest;
	private TextView OrderPrompt_Order;
	private CheckBox OrderPrompt_Next;	
	
	//private ImageView OrderPrompt_GoodsImage;
	
	private ImageSwitcher OrderPrompt_GoodsImage;
	
	private TextView order_rest_tv;
	private TextView order_order_tv;	
	
	private TextView OrderRuleTextView;
	
	private TextView CountertextView;
	
	private Button OrderPromptAddActions;
	
	private Cursor GoodsMeasures;
	
	private Documents_Order DocumentClass; 
	
	private ArrayList<GoodsRefItem> GoodsRef;
	private GoodsRefItem GoodsItem;
	
	private ArrayList<SalesRefItem> SalesRef;
	
	private SalesRefItem SalesItem;
	
	private int GoodsRefPosition; 
	
	private Drawable Img;
	
	private boolean FormUpdated;
	
	private TextView MeasuresTextView;
	
	private String DivsArray []; 
	
	private TextView GoodsDivs;
	
	private void GetGoodDivs () {
		
		GoodsDivs.setVisibility(View.INVISIBLE);
		String DivsString = "";		
		DivsArray = new String []{};
		
		Cursor CursorDivs = MainGlobalModule.DBE.rawQuery("select divs from xref_goodsdivs where goods_id = ?", new String [] {GoodsItem.id});
		if (CursorDivs.getCount()>0) {
			CursorDivs.moveToFirst();
			DivsString = CursorDivs.getString(0);
			DivsArray = DivsString.split(",");			
		}
		
		if (DivsArray.length>0) {
			GoodsDivs.setText(String.format("Кратность:%s", DivsString));
			GoodsDivs.setVisibility(View.VISIBLE);	
		}
		
	}
	
	private Runnable ImageDraw = new Runnable() {
		
        public void run() {
     	   
    	    File ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.GoodsImagesPath,GoodsItem.id.trim()));
    	    
      	 		if (ImgPath.exists()) {
      	 			Img = Drawable.createFromPath(ImgPath.getAbsolutePath());
      	 			OrderPrompt_GoodsImage.post(new Runnable() {
          	 			public void run() {
          	 				OrderPrompt_GoodsImage.setImageDrawable(Img);              	 				
          	 			}});		
      	 		}
      	 		else
      	 		{
      	 			OrderPrompt_GoodsImage.post(new Runnable() {
      	 				public void run() {
  	 						OrderPrompt_GoodsImage.setImageResource(R.drawable.st_goods);
      	 				}});      	 			
      	 		}
        }
	};

	
	private void GetDataByBundle (int move_value) {		

		
		FormUpdated = false;
		
		GoodsRefPosition+=move_value;
		if ((GoodsRefPosition>-1) & (GoodsRefPosition<GoodsRef.size())) {			
			if (GoodsRef.get(GoodsRefPosition).isfolder==1) {
				GetDataByBundle (move_value);				
			}			
		}
		else {			
			GetDataByBundle (-move_value);
		}
		
		GoodsRefItem OldGoodsItem = GoodsItem;		
		GoodsItem = GoodsRef.get(GoodsRefPosition);
		
		if (OldGoodsItem!=null&&OldGoodsItem.equals(GoodsItem)&move_value!=0) {
			return;
		}
		
		GetGoodDivs ();
		
		DocumentClass.SetLineDocByGoodRefItem(GoodsItem);
		
		SalesItem = DocumentClass.SalesCollection.get(GoodsItem.id);
	    if (SalesItem==null) {
	    	SalesItem = new SalesRefItem(0.0, 0.0);
	    }
		

		if (move_value>0) {
			OrderPrompt_GoodsImage.setInAnimation(slide_in_right);
			OrderPrompt_GoodsImage.setOutAnimation(slide_out_right);
		}
		else
		{
			OrderPrompt_GoodsImage.setInAnimation(slide_in_left);
			OrderPrompt_GoodsImage.setOutAnimation(slide_out_left);			
		}

	    Thread myThread = new Thread(ImageDraw);
		myThread.run();
	    
		OrderPrompt_GoodsDescr.setText(String.format("%s",GoodsItem.descr));
		
		order_rest_tv.setVisibility(SalesItem.sales_rest>0?View.VISIBLE:View.INVISIBLE);
		order_order_tv.setVisibility(SalesItem.sales_order>0?View.VISIBLE:View.INVISIBLE);	
		
		order_rest_tv.setText(String.format ("%.1f %s(%.1f)",SalesItem.sales_rest,GoodsItem.measure_base_descr,GoodsItem.measure_base_factor));		
		order_order_tv.setText(String.format ("%.1f %s(%.1f)",SalesItem.sales_order,GoodsItem.measure_base_descr,GoodsItem.measure_base_factor));		
		
		OrderPrompt_GoodsDescr.setTextColor(Color.WHITE);		
		OrderPrompt_Price.setTextColor(Color.WHITE);
		OrderPrompt_GoodsRest.setTextColor(Color.WHITE);		
		OrderRuleTextView.setVisibility(View.INVISIBLE);
	
		OrderPrompt_Rest.setText(String.valueOf(DocumentClass.Line.restvalue));			

		MeasuresTextView = (TextView)findViewById(R.id.MeasuresTextView01);		
		
		if (GoodsItem.rest<=0) {
			OrderPrompt_GoodsDescr.setTextColor(Color.DKGRAY);
			OrderPrompt_Price.setTextColor(Color.DKGRAY);
			OrderPrompt_GoodsRest.setTextColor(Color.DKGRAY);
		}
		
		//if (!(DocumentClass.AssortmentsCollection.get(GoodsItem.id)==null)) {			
		//	RecalculateOrderByRule (false);			
		//	OrderPrompt_GoodsDescr.setTextColor(Color.RED);			
		//}
		
		if (MainGlobalModule.SettingsCollection.get("RestOrderPref").equals("0")) {
			OrderPrompt_Rest.requestFocus();
			OrderPrompt_Rest.setSelected(true);
		}
		else
		{
			OrderPrompt_Order.requestFocus();	
			OrderPrompt_Order.setSelected(true);
		}		
        
		OrderPrompt_Order.setText(String.valueOf(DocumentClass.Line.ordervalue));		
		
             
        GetMeasuresCursor ();        
        
        StringBuilder sb = new StringBuilder();       		
        
        int mp = 0;
        for (int i = 0;i<GoodsMeasures.getCount();i++) {
        	GoodsMeasures.moveToPosition(i);
        	sb.append(GoodsMeasures.getString(1));
        	sb.append("/");
        	if (GoodsMeasures.getString(0).equals(DocumentClass.Line.goods_measures_id)){
        		mp = i;
        	}
        }
        
		GoodsMeasures.moveToPosition(mp);
    	OrderPrompt_Measures.setText(GoodsMeasures.getString(1)); 
    	
    	OrderPrompt_GoodsRest.setText(String.format("%.2f",GoodsItem.rest/DocumentClass.Line.factor));    	
		OrderPrompt_Price.setText(String.format("%.2f",GoodsItem.price*DocumentClass.Line.factor));
    	
    	MeasuresTextView.setText(sb.toString());
    	
    	CountertextView.setText(String.format("%d из %d", GoodsRefPosition+1,GoodsRef.size()));
    	
    	if (GoodsItem.rule_factor>0){	
			OrderRuleTextView.setText(String.format("Прав:%.2f", GoodsItem.rule_factor));
			OrderRuleTextView.setVisibility(View.VISIBLE);
    	}
    	
    	
	}

	private void RecalculateOrderByRest () {
				
		if (GetFocusedTextView().equals(OrderPrompt_Rest)){
			RecalculateOrderByRule (true);			
		}
		
	}
	
	private void RecalculateOrderByRule (boolean force) {
		
		double dRest = Double.parseDouble(OrderPrompt_Rest.getText().toString());
		
		if (GoodsItem.rule_factor>0){	
			OrderRuleTextView.setText(String.format("Прав:%.2f", GoodsItem.rule_factor));
			OrderRuleTextView.setVisibility(View.VISIBLE);
			if (DocumentClass.Line.ordervalue==0|force){
				DocumentClass.Line.ordervalue = Math.round(((SalesItem.sales_rest+SalesItem.sales_order-dRest)*GoodsItem.rule_factor)/DocumentClass.Line.factor);				
				if (DocumentClass.Line.ordervalue<=0) {
					DocumentClass.Line.ordervalue=0;
				}				
				else {
					FormUpdated = true;
					Toast xtoast = Toast.makeText(this, "Заказ рассчитан автоматически !!!", Toast.LENGTH_SHORT);
					xtoast.show();	
					Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
					vb.vibrate(10);
				}
				OrderPrompt_Order.setText(String.valueOf(DocumentClass.Line.ordervalue));
			}
		}		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) < Configuration.SCREENLAYOUT_SIZE_LARGE) {			
			setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);			
		}
		
		super.onCreate(savedInstanceState);
	
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.prompt_order_goods);	
		
	    Ctx = this;
	    
	    GoodsRefPosition = getIntent().getExtras().getInt("GoodsRefPosition");	    
	    GoodsRef = MainGlobalModule.GoodsRef;
		
	    DocumentClass = (Documents_Order)MainGlobalModule.DocumentClass;
		
		order_rest_tv = (TextView)findViewById(R.id.order_rest_tv);
		
		order_order_tv = (TextView)findViewById(R.id.order_order_tv);

		OrderPrompt_One = (Button)findViewById(R.id.OrderPrompt_One);
		OrderPrompt_One.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Two = (Button)findViewById(R.id.OrderPrompt_Two);
		OrderPrompt_Two.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Three = (Button)findViewById(R.id.OrderPrompt_Three);
		OrderPrompt_Three.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Four = (Button)findViewById(R.id.OrderPrompt_Four);
		OrderPrompt_Four.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Five = (Button)findViewById(R.id.OrderPrompt_Five);
		OrderPrompt_Five.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Six = (Button)findViewById(R.id.OrderPrompt_Six);
		OrderPrompt_Six.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Seven = (Button)findViewById(R.id.OrderPrompt_Seven);
		OrderPrompt_Seven.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Eight = (Button)findViewById(R.id.OrderPrompt_Eight);
		OrderPrompt_Eight.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Nine = (Button)findViewById(R.id.OrderPrompt_Nine);
		OrderPrompt_Nine.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Null = (Button)findViewById(R.id.OrderPrompt_Null);
		OrderPrompt_Null.setOnClickListener(OrderPrompt_Number_Click);
		
		OrderPrompt_Enter = (Button)findViewById(R.id.OrderPrompt_Enter);
		OrderPrompt_Enter.setOnClickListener(OrderPrompt_Enter_Click);		
		
		OrderPrompt_Clear = (Button)findViewById(R.id.OrderPrompt_Clear);
		OrderPrompt_Clear.setOnClickListener(OrderPrompt_Clear_Click);
		
		OrderPrompt_BackSpace = (Button)findViewById(R.id.OrderPrompt_BackSpace);
		OrderPrompt_BackSpace.setOnClickListener(OrderPrompt_BackSpace_Click); 
		
		OrderPrompt_Point = (Button)findViewById(R.id.OrderPrompt_Point);
		OrderPrompt_Point.setOnClickListener(OrderPrompt__Point_Click);		
		
		OrderPrompt_Rest = (TextView)findViewById(R.id.OrderPrompt_Rest);
		OrderPrompt_Order = (TextView)findViewById(R.id.OrderPrompt_Order);		
		
		OrderPrompt_Measures = (Button)findViewById(R.id.OrderPrompt_OrderMeasures);
		OrderPrompt_Measures.setOnClickListener(OrderPrompt_Measures_Click);		
		
		OrderPrompt_GoodsDescr = (TextView)findViewById(R.id.OrderPrompt_GoodsDescr);		
		
		OrderPrompt_Price = (TextView)findViewById(R.id.OrderPrompt_Price);		
		
		OrderPrompt_GoodsRest = (TextView)findViewById(R.id.OrderPrompt_GoodsRest);			
		
		OrderPrompt_Rest = (TextView)findViewById(R.id.OrderPrompt_Rest);		
		
		OrderPrompt_Rest.setInputType(InputType.TYPE_NULL);
		OrderPrompt_Rest.setOnFocusChangeListener(FieldOnFocusChange);		
		
		OrderPrompt_Order = (TextView)findViewById(R.id.OrderPrompt_Order);
		OrderPrompt_Order.setInputType(InputType.TYPE_NULL);			
		OrderPrompt_Order.setOnFocusChangeListener(FieldOnFocusChange);


		
		OrderPrompt_Order.setOnLongClickListener(OrderRestLongClickListener);
		OrderPrompt_Rest.setOnLongClickListener(OrderRestLongClickListener);		
		
		OrderPrompt_GoodsImage = (ImageSwitcher)findViewById(R.id.OrderPrompt_GoodsImage);	
		OrderPrompt_GoodsImage.setFactory(new ViewFactory() {

			@Override
			public View makeView() {

				ImageView imageView = new ImageView(Ctx);
				imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
				imageView.setAdjustViewBounds(true);
				LayoutParams params = new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
				imageView.setLayoutParams(params);
				return imageView;
				
			}
		});
		
		
		CountertextView = (TextView)findViewById(R.id.CounterTextView);
		
		OrderRuleTextView = (TextView)findViewById(R.id.OrderRuleTextView);
		OrderRuleTextView.setVisibility(View.INVISIBLE);
		
		OrderPromptAddActions = (Button)findViewById(R.id.OrderPromptAddActions);
		OrderPromptAddActions.setOnClickListener(OrderPromptAddActions_Click);
		
		GoodsDivs = (TextView)findViewById(R.id.GoodsDivs);
		GoodsDivs.setVisibility(View.INVISIBLE);
		
		GetDataByBundle(0);
				
		OrderPrompt_GoodsImage.setOnTouchListener(ImageTouchListener);

		slide_in_left = AnimationUtils.loadAnimation(this,R.anim.in_l);		
		slide_out_left = AnimationUtils.loadAnimation(this,R.anim.out_l);		
		
		slide_in_right = AnimationUtils.loadAnimation(this,R.anim.in_r);		
		slide_out_right = AnimationUtils.loadAnimation(this,R.anim.out_r);		
		
		OrderPrompt_GoodsImage.setInAnimation(slide_in_right);
		OrderPrompt_GoodsImage.setOutAnimation(slide_out_right);
		
		 Thread myThread = new Thread(ImageDraw);
		 myThread.run();
		
	}
	
	private OnTouchListener ImageTouchListener = new OnTouchListener() {		
		

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			
			int X = (int) event.getX();			

			int eventaction = event.getAction();

			switch (eventaction) {

			case MotionEvent.ACTION_DOWN:				
				
				if ((v.getWidth()/2)>X) {
					SaveData(-1,false);
				}
				else
				{
					SaveData(1,false);
				}
			    break;				
			}
			
			return true;
		}
	};	
	
	private OnClickListener OrderPromptAddActions_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			
			AlertDialog.Builder builder = new AlertDialog.Builder(Ctx);
			builder.setItems(new String []{"Доп. инфо к строке","Источник цены","История продаж"}, OrderPromptAddActionsDialog_Listener);
			Dialog alert = builder.create();
			alert.show();
			
		}
	};
	
	private DialogInterface.OnClickListener OrderPromptAddActionsDialog_Listener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	
	    	switch (which) {
			case 0:
				
				Intent OrderGoodDetailsIntent = new Intent ();
				OrderGoodDetailsIntent.setClass(Ctx,Activity_OrderGoodsDetails.class);
				
				startActivityForResult(OrderGoodDetailsIntent, 0);
				
				break;
			case 2:
				
				Intent SalesHistoryIntent = new Intent ();
				SalesHistoryIntent.setClass(Ctx,Activity_SalesHistory.class);				
				SalesHistoryIntent.putExtra("GoodsId", GoodsItem.id);
				SalesHistoryIntent.putExtra("GoodsDescr", GoodsItem.descr);
				SalesHistoryIntent.putExtra("CustomersId", DocumentClass.Head.customers_id);
				SalesHistoryIntent.putExtra("CustomersDescr", "");				
				startActivityForResult(SalesHistoryIntent, 0);
				
				break;
			default:
				break;
			}
	    	
	    	
	    	
	    }		
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		
		
	};
	
	private OnLongClickListener OrderRestLongClickListener = new  OnLongClickListener() {		
		@Override
		public boolean onLongClick(View v) {

			if (v.equals(OrderPrompt_Order)){
				MainGlobalModule.SettingsCollection_Update ("RestOrderPref", "1");
			}
			else
			{
				MainGlobalModule.SettingsCollection_Update ("RestOrderPref", "0");
			}
			
			Toast xtoast = Toast.makeText(Ctx, "Настройка сохранена", 10);
			xtoast.show();
			
			return true;
			
		}
	}; 
	
	private OnFocusChangeListener FieldOnFocusChange = new OnFocusChangeListener() {		
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			v.setSelected(hasFocus);
		}
	}; 
	
		
	private void SaveDataToDocument () {
	
		DocumentClass.Line.restvalue = Double.parseDouble(OrderPrompt_Rest.getText().toString());
		DocumentClass.Line.ordervalue = Double.parseDouble(OrderPrompt_Order.getText().toString());			
		DocumentClass.Line.rest_sum = DocumentClass.Line.price*GoodsItem.measure_base_factor* DocumentClass.Line.restvalue; 
		DocumentClass.Line.order_sum = DocumentClass.Line.price*DocumentClass.Line.factor * DocumentClass.Line.ordervalue;				
		DocumentClass.InsertUpdateLine();
		
	}
	
	private void SaveData (final int move,final boolean finish) {
		
		if (MainGlobalModule.ExistsOffersByGoodsId (DocumentClass.Head.id,GoodsItem.id)) {
			Toast.makeText(this, "Товар использован в акции, используйте подбор по акции !", Toast.LENGTH_LONG).show();			
		}
		else
		{			
			if (FormUpdated) {				
				MainGlobalModule.Vibrate ();				
				if (GoodsItem.rest<Double.parseDouble(OrderPrompt_Order.getText().toString())) {
					AlertDialog.Builder adb = new AlertDialog.Builder(this);
					adb.setTitle("Недостаточно товара на складе !");
					adb.setPositiveButton("Продолжить", new DialogInterface.OnClickListener() {						
						@Override
						public void onClick(DialogInterface dialog, int which) {							
							dialog.dismiss();							
							SaveDataToDocument ();
							if (finish)FinishActivity();
							if (move!=0){
								GetDataByBundle(move);
							}
						}
					});	
					adb.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							GetFocusedTextView ().setSelected(false);
						}
					});
					adb.show();	
				}				
				else
				{
					SaveDataToDocument ();					
					if (finish)FinishActivity();
					if (move!=0){
						GetDataByBundle(move);
					}
				}				
					
			}
			else
			{
				if (finish)FinishActivity();
				if (move!=0){
					GetDataByBundle(move);
				}	
			}
		}		
	}
	
	private void FinishActivity () {
		
		Intent DataIntent = new Intent ();
		setResult(RESULT_OK, DataIntent);
		DataIntent.putExtra("GoodsRefPosition", GoodsRefPosition);		
		finish();
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		if (keyCode==KeyEvent.KEYCODE_BACK) {
			FinishActivity();
		}
		
		return super.onKeyDown(keyCode, event);
		
	}
	
	private OnClickListener OrderPrompt_Enter_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {						
			FormUpdated = true;
			SaveData(0,true);
		}
	};
	
	private TextView GetFocusedTextView () {
		
		if (OrderPrompt_Rest.isFocused()) {return (OrderPrompt_Rest);}
		if (OrderPrompt_Order.isFocused()) {return (OrderPrompt_Order);}
		if (OrderPrompt_Next.isFocused()) {return (OrderPrompt_Next);}
		
		return null;
		
	}
	
	private OnClickListener OrderPrompt_Number_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {
		
			FormUpdated = true;			
			
			Button NumberButton = (Button)v;
			String NumberButtonText = (String) NumberButton.getText();
			
			TextView FocusedTextView = GetFocusedTextView ();			
			
			String FocusedTextViewText = (String) FocusedTextView.getText().toString();
			
			if (FocusedTextView.isSelected()) {
				FocusedTextViewText = "";
				FocusedTextView.setSelected(false);				
			}
			
			if (FocusedTextViewText.equals("0")) {
				FocusedTextView.setText(NumberButtonText);
			}
			else {
				FocusedTextView.setText(FocusedTextViewText.concat(NumberButtonText));
			}			
			
			
			RecalculateOrderByRest ();
			
		}
	};
	
	private OnClickListener OrderPrompt_Clear_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {
		
			FormUpdated = true;
					
			TextView FocusedTextView = GetFocusedTextView ();
			FocusedTextView.setText("0");			
			
			RecalculateOrderByRest ();
			
		}
	};
	
	private OnClickListener OrderPrompt__Point_Click= new OnClickListener() {
		@Override
		public void onClick(View v) {

			FormUpdated = true;
		
			TextView FocusedTextView = GetFocusedTextView ();
			
			Button NumberButton = (Button)v;
			String NumberButtonText = (String) NumberButton.getText();
			
			String FocusedTextViewText = (String) FocusedTextView.getText().toString();

			if (FocusedTextView.isSelected()) {
				FocusedTextViewText = "0.";
				FocusedTextView.setSelected(false);	
				return;
			}	
			
			if (FocusedTextViewText.contains(".")!=true) {
				FocusedTextView.setText(FocusedTextViewText.concat(NumberButtonText));					
			}
			
			RecalculateOrderByRest ();
		}
	};
	
	private OnClickListener OrderPrompt_BackSpace_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {
		
			FormUpdated = true;			
			
			TextView FocusedTextView = GetFocusedTextView ();
			
			String FocusedTextViewText = FocusedTextView.getText().toString();
			
			if (FocusedTextView.isSelected()) {
				FocusedTextViewText = "";
				FocusedTextView.setSelected(false);
			}
			
			if (FocusedTextViewText.length() > 1) {
				FocusedTextView.setText(FocusedTextViewText.substring(0, FocusedTextViewText.length()-1));	
			}
			else {
				FocusedTextView.setText("0");
			}			
			
			RecalculateOrderByRest ();
			
		}
	};	
	
	private boolean GetMeasuresCursor () {
		
		try {
			GoodsMeasures = MainGlobalModule.DBE.rawQuery("select a.id as _id,   b.descr || '(' || a.mul || ')' as descr , a.mul as mul , b.descr as odescr from xref_GoodsMeasures a left outer join xref_Measures b on a.measures_id = b.id where a.goods_id = ? order by a.mul asc", new String [] {GoodsItem.id});
			return (true);
		} catch (Exception e) {
			return (false);
		}
		
	}
	
	private OnClickListener OrderPrompt_Measures_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {
			
			AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);
			adb.setTitle("Единицы");
			adb.setCursor(GoodsMeasures, OrderPrompt_MeasuresDialogClickListener , "descr");			
			adb.show();
			
		}
	};		
		
	private DialogInterface.OnClickListener OrderPrompt_MeasuresDialogClickListener = new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int which) {
		    	
		    	GoodsMeasures.moveToPosition(which);
		    	OrderPrompt_Measures.setText(GoodsMeasures.getString(1));	    	
		    	
		    	DocumentClass.Line.factor = GoodsMeasures.getDouble(2);
		    	DocumentClass.Line.goods_measures_descr = GoodsMeasures.getString (3);
		    	DocumentClass.Line.goods_measures_id = GoodsMeasures.getString (0);		    	
		    	
		    	OrderPrompt_GoodsRest.setText(String.format("%.2f",GoodsItem.rest/DocumentClass.Line.factor));
		    	
				OrderPrompt_Price.setText(String.format("%.2f",GoodsItem.price*DocumentClass.Line.factor));
		    
		    	RecalculateOrderByRest ();
		    	
		    	dialog.dismiss();
		    	
			}
		};
		
}
